// index.js
// 获取应用实例
var QQMapWX = require('../js/qqmap-wx-jssdk.min.js');
var qqmapsdk;
const app = getApp()

Page({
  data: {
      swiperList: [],
      hotList: [],
      navIcons: {},
      pageNum: 1,
      isLastPage: false,
      isLoad: false,
      priceNameInfo: {},
      cityName: '',
      cityCode: '',
      isOpen: false,
      allCityList: [],
      cityList: [],
      localCity:{},
      pOpenid: '',
  },
  
  onLoad(query) {
    var that = this
    //var carList = app.globalData.carList
    //this.setData({hotList: carList,navIcons:app.globalData.publicIcon})
    qqmapsdk = new QQMapWX({
        key: 'OWNBZ-TWE3I-5UOGJ-5QLJZ-QJMVV-SPF4Z'
    });
    this.setData({navIcons:app.globalData.publicIcon})
    
    const scene = decodeURIComponent(query.scene)
    //const scene = 'testPopenid'
    console.log('来自分享，分享者：'+scene,'我的登录信息：'+ app.globalData.openid)
    app.globalData.pOpenid = scene
    this.setData({priceNameInfo: app.globalData.priceNameInfo,pOpenid:scene})
    
    this.getUserLocation()  
    

    // qqmapsdk.getCityList({
    //     success: function(res) {//成功后的回调
    //       console.log('城市数据：', JSON.stringify(res.result[1])); //打印城市数据
    //     },
    //     fail: function(error) {
    //       console.error(error);
    //     },
    //     complete: function(res) {
    //       console.log(res);
    //     }
    // })
    //wx.setStorageSync('pOpenid', scene)

  },
    /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.isLastPage){
      return false;
    }
    var pageNum = this.data.pageNum+1;
    this.setData({pageNum:pageNum})
    this.getHotProduct()
  },


  jumpPage: function(param){
    wx.navigateTo({ url: param.currentTarget.dataset.path})
  },
  getHotProduct: function(){
      var that = this
      //var cityCode = wx.getStorageSync('local_city_code')
      var cityCode = this.data.cityCode
      that.setData({isLoad: true})
      wx.request({
        url: app.globalData.apiPath + 'product/hotList',
        method: 'POST',
        data: {cityCode: cityCode,pageNum: that.data.pageNum,pageSize: 10},
        success (res) {
          var pageList = res.data.data.records;
          //for(var i=0;i<pageList.lenght;)
          pageList.forEach((item,index) => {
             item.mainImg = JSON.parse(item.mainImg)
             item.detailImgs = JSON.parse(item.detailImgs)
             item.label = JSON.parse(item.label)
             if(item.productPriceList.length > 0){
                item.defaultPrice = item.productPriceList[0].price
             }
          })
          var list = that.data.hotList.concat(pageList);
          that.setData({hotList:list,isLoad: false})
          if(that.data.pageNum == res.data.data.pages){
            that.setData({isLastPage:true})
          }
          console.log(cityCode,list.length)
          //判断当前城市数据是否为空
          var cityTips = wx.getStorageSync("cityTips")
          if((cityCode != null && cityCode != '') && list.length == 0 && cityTips != 1){
            wx.showModal({
              title: '提示',
              content: '当前城市'+that.data.cityName+'尚未上架车辆，是否切换城市？',
              confirmText: '切换城市',
              cancelText: '不再提醒',
              confirmColor: '#e54d42',
              success (res2) {
                wx.setStorageSync('cityTips', 1);
                if (res2.confirm) {
                  
                  that.openChangeCity()
                } else if (res2.cancel) {
                  
                }
              }
            })
          }
        }
      })
  },
  getBanner: function(){
      var that = this
      wx.request({
        url: app.globalData.apiPath + 'banner/list',
        method: 'POST',
        data: {type:1},
        success (res) {
          var list = res.data.data;
          that.setData({swiperList:list})
        }
      })
  },
  getCityList: function(){
    var that = this
    wx.request({
      url: app.globalData.apiPath + 'treeDict/dictList',
      method: 'POST',
      data: {typeCode: 'cityPrice'},
      success (res) {
        var list = res.data.data
        var local_city_code = wx.getStorageSync('local_city_code')
        var hotCity = []
        list.forEach((item,index) => {
          if(item.code != local_city_code){
            hotCity.push(item)
          }
        })
        that.setData({cityList: hotCity,allCityList:list})
      }
    })
  },
  toCarTab: function(){
    wx.switchTab({
      url: '/pages/car/index'
    })
  },
  checkAuth(callback) {
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              wx.getLocation({
                type: 'wgs84',
                success(res1) {
                  callback(res1.latitude, res1.longitude)
                }
              })
            }
          })
        }else{
          wx.getLocation({
            type: 'wgs84',
            success(res1) {
              callback(res1.latitude, res1.longitude)
            }
          })
        }
      }
    })
  },
  getUserLocation(){
    var that = this
    // var local_city_code = wx.getStorageSync('local_city_code')
    // var local_city = wx.getStorageSync('local_city')
    // if(local_city_code != null && local_city_code != ''){
    //   that.setData({cityCode : local_city_code,cityName : local_city}) 
    //   that.getBanner()
    //   that.getHotProduct()
    //   that.getCityList()
    //   return false;
    // }
    this.checkAuth(function(lat,lon){
        qqmapsdk.reverseGeocoder({
            location: {latitude:lat, longitude:lon},
            success(res) {
              console.log(cityCode,that.data.localCity)
              
              var cityTips = wx.getStorageSync("cityTips")
              if(cityTips != 1){
                var cityCode = res.result.ad_info.city_code,cityName = res.result.ad_info.city
                var localCity = {cityCode : cityCode,cityName : cityName}
                that.setData({cityCode : cityCode,cityName : cityName,localCity: localCity}) 
                wx.setStorageSync('local_city', res.result.ad_info.city)
                wx.setStorageSync('local_city_code', res.result.ad_info.city_code)
                wx.setStorageSync('localCity', localCity)
              }else{
                var cityCode = wx.getStorageSync('local_city_code'),cityName = wx.getStorageSync('local_city'),localCity = wx.getStorageSync('localCity')
                that.setData({cityCode : cityCode,cityName : cityName,localCity:localCity}) 
              }
              
            },
            fail(err) {
              wx.showToast('获取城市失败')
            },
            complete() {
              // 做点什么
              that.getBanner()
              that.getHotProduct()
              that.getCityList()
            }
          })
      })
  },
  changeCity: function(e){
      var code = e.currentTarget.dataset.code
      var name = e.currentTarget.dataset.name
      this.setData({cityCode:code,cityName:name,isOpen: false,hotList: []});
      wx.setStorageSync('local_city', name)
      wx.setStorageSync('local_city_code', code)
      this.getBanner()
      this.getHotProduct()
      var list = this.data.allCityList
      var hotCity = []
      list.forEach((item,index) => {
        if(item.code != code){
          hotCity.push(item)
        }
      })
      this.setData({cityList: hotCity})
      wx.showToast({
        title: '已切换到'+name,
        icon: 'none',
        duration: 3000
      })
  },
  openChangeCity: function(){
    this.setData({isOpen:true})
  },
  hideOpen: function(){
    this.setData({isOpen:false})
  },
  bannerClick: function(e){
      var index = e.currentTarget.dataset.index
      var bannerInfo = this.data.swiperList[index]
      if(bannerInfo.linkType == 1){
        //汽车详情页
        wx.navigateTo({ url: '/pages/detail/detail?id='+bannerInfo.linkUrl})
      }else if(bannerInfo.linkType == 2){
        //内部页面
        wx.navigateTo({ url: bannerInfo.linkUrl})
      }else if(bannerInfo.linkType == 3){
        //外部链接
        wx.navigateTo({ url: '/pages/H5Page/H5Page?link='+bannerInfo.linkUrl})
      }
  },

})
